import 'package:flutter/material.dart';
import '../models/book.dart';
import '../pages/book_detail_page.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class BookshelfPage extends StatefulWidget {
  const BookshelfPage({super.key});

  @override
  State<BookshelfPage> createState() => _BookshelfPageState();
}

class _BookshelfPageState extends State<BookshelfPage> {
  List<Book> _books = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadBooks();
  }

  Future<void> _loadBooks() async {
    final prefs = await SharedPreferences.getInstance();
    final booksJson = prefs.getStringList('books') ?? [];
    setState(() {
      _books = booksJson.map((e) => Book.fromJson(json.decode(e))).toList();
      _loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    final List<Widget> bookTiles = [];
    // Web端临时epub显示
    // ... 这里可根据主项目需求补充 ...
    bookTiles.addAll(
      _books.map(
        (book) => ListTile(
          leading: Icon(book.type == 'txt' ? Icons.menu_book : Icons.image),
          title: Text(book.name),
          subtitle: Text(book.type == 'txt' ? '小说 (txt)' : '漫画 (epub)'),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (_) => BookDetailPage(book: book)),
            );
          },
        ),
      ),
    );
    return Scaffold(
      appBar: AppBar(title: const Text('书架')),
      body:
          _loading
              ? const Center(child: CircularProgressIndicator())
              : bookTiles.isEmpty
              ? const Center(child: Text('暂无书籍'))
              : ListView(children: bookTiles),
    );
  }
} 